package com.dib.neo.bkfs.config;

import com.google.common.collect.Maps;
import org.apache.commons.text.StringSubstitutor;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public enum PropertiesHelper {
  helper;
  public String relace(String value,  Map<String,Object>  map){
    return relace(value,true, map);
  }

  public String relace(String value, Properties props){
    return relace(value,true, props);
  }
  public String relace(String value, boolean searchSystemProps, Properties props){
    Map<String,Object> properties = new HashMap<>();
    if(props!=null&&props.size()>0){
      props.forEach((k,v)->{if(k!=null)properties.put(k.toString(),v);});
    }
    return relace(value,searchSystemProps,properties);
  }

  public String relace(String value, boolean searchSystemProps, Map<String,Object>  map){
    Map<String,Object> properties = new HashMap<>();
    if(map!=null&&map.size()>0){
      properties.putAll(map);
    }
    if(searchSystemProps){
      System.getProperties().forEach((k,v)->{if(k!=null)properties.put(k.toString(),v);});
    }
    StringSubstitutor sub = new StringSubstitutor(properties);
    sub.setEnableSubstitutionInVariables(true);
    sub.setValueDelimiter(':');
    try {
      String rvalue = sub.replace(value);
      return rvalue;
    }finally{
      properties.clear();
    }
  }


  public static void main(String[] args) {
    Map<String,Object> map = Maps.newHashMap();
    //System.setProperty("dirname","datadir");
    System.setProperty("datadir","${user.dir}/data");
    String v = PropertiesHelper.helper.relace("${${dirname:datadir}}/zookeeper/${filename:bookies}",map);
    System.out.println("v = " + v);
  }



}
